

public class Leetcode868 {
    public static void main(String[] args) {
        System.out.println(binaryGap(22));
        System.out.println(binaryGap(8));
        System.out.println(binaryGap(5));
    }

    public static int binaryGap(int n) {
        int res = 0;
        int current = 1;
        boolean start = false;
        for (int i = 31; i > -1; i--) {
            if ((n & (1 << i)) != 0) {
                if (start) {
                    res = Math.max(current, res);
                }

                current = 1;
                start = true;
                continue;
            }

            if (start) {
                current++;
            }
        }

        return res;
    }
}
